package com.hns.can.energy.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hns.can.base.entity.SysUserEntity;
import com.hns.can.common.aop.orgTree.LeftOrgAnnotation;
import com.hns.can.common.constants.GlobalConst;
import com.hns.can.common.formula.FillCodeDscValue;
import com.hns.can.common.formula.FillParamsVo;
import com.hns.can.energy.entity.AppOilPriceEntity;
import com.hns.can.energy.entity.EaiIttriplogEntity;
import com.hns.can.energy.vo.EaiIttriplogTabVo;
import com.hns.can.energy.vo.EleDetailVo;
import com.hns.can.energy.vo.ParamVo;
import com.hns.frame.mybatis.Pagination;
import com.hns.frame.service.CommonService;
import com.hns.tool.pub.PubUtil;

/**
 * 电子更纸明细service
 * @author:Fisher
 * @email:zhuangcaijin@126.com
 * @version Revision 2.0.0
 */
@Service
public class EleDetailService extends CommonService {
    
    @Autowired
    private FillCodeDscValue codeDscValue;
    private final Logger              logger = LoggerFactory.getLogger(EleDetailService.class);

    /**
     *  查询
     * @param conditionVo
     * @return
     * @throws Exception
     */
    @LeftOrgAnnotation()
    @Transactional
    public Pagination searchEleDetail(ParamVo paramVo) throws Exception {
        Pagination page = this.myBatisPage("eleDetail.searchEleDetailCnt", "eleDetail.searchEleDetailData", paramVo,EleDetailVo.class);
        Map<String,String> map = new HashMap<String,String>();
        return page;
    }

    /**
     * 导出
     * @param conditionVo
     * @return
     * @throws Exception
     */
    @LeftOrgAnnotation()
    @Transactional
    public List<EaiIttriplogEntity> exportEleDetail(ParamVo vo) throws Exception {
        List list = PubUtil.convertListMapToObject(sqlMapDao.selectList("eleDetail.searchEleDetailData", vo), EleDetailVo.class);
        Map<String,String> map = new HashMap<String,String>();
        map.put("licPltNo", GlobalConst.DEFAULT_CACHE_VALUE);
        FillParamsVo vo2 = new FillParamsVo("carId", map);
        codeDscValue.fillInfoValue(list, new String[]{GlobalConst.CACHE_KEY_BASE_CAR_INFO}, vo2);
        return list;
    }
    
    /**
     * 导入珍宝电子更纸
     * @param list
     * @param user
     * @param corpId
     * @param orgId
     * @throws Exception
     */
    @Transactional(rollbackFor=Exception.class)
    public int saveZhenBaoToDB(List<EaiIttriplogEntity> list, SysUserEntity user,String corpId,String orgId) throws Exception {
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	SimpleDateFormat idSdf=new SimpleDateFormat("yyyyMMddHHmmss");
    	String updatetime=sdf.format(new Date());
    	int count = 0;
    	Map<String,String> mapId = new HashMap<String,String>();
    	//为避免客户重新插入,将原来的数据删除再插入,也避免重复数据
    	for(int i=0;i<list.size();i++){
    		EaiIttriplogEntity entity = list.get(i);
    		Date date = sdf.parse(entity.getDispatchstarttime());
    		String str=idSdf.format(date);
    		String rcrdId=entity.getRoutecoderun()+entity.getBuscodeforshort()+str;
    		mapId.put("rcrdId", rcrdId);
    		//利用主键删除
    		this.sqlMapDao.delete("eleDetail.deleteById", mapId);
    	}
    	for(EaiIttriplogEntity entity:list){
    		count++;
    		//生成主键  
    		Date date = sdf.parse(entity.getDispatchstarttime());
    		String str=idSdf.format(date);
    		String rcrdId=entity.getRoutecoderun()+entity.getBuscodeforshort()+str;
    		entity.setRcrdId(rcrdId);
    		Map<String,String> map = new HashMap<String,String>();
    		entity.setUpdatename(user.getAcctName());
    		entity.setUpdatetime(updatetime);
    		//获取carId
    		String buscodeforshort = entity.getBuscodeforshort();
    		map.put("buscodeforshort", buscodeforshort);
    		Map<String, String> result = (Map<String, String>) sqlMapDao.selectOne("eleDetail.searchCarId", map);
    		if(!PubUtil.isEmpty(result)){
    			entity.setCarId(result.get("CAR_ID"));
    		}
    		//获取发出站点编码
    		String startstopname=entity.getStartstopname();
    		String rundirection=entity.getRundirection();
    		if("0".equals(rundirection)){
    			rundirection="上行";
    		}else if("1".equals(rundirection)){
    			rundirection="下行";
    		}else{
    			rundirection="无方向";
    		}
    		String startstopCode=getStationCode(startstopname,rundirection);
    		entity.setStartstopcode(startstopCode);
    		//获取终点站编码
    		String destinationname=entity.getDestinationname();
    		String destinationCode = getStationCode(destinationname,rundirection);
    		entity.setDestinationcode(destinationCode);
    		//添加机构id
    		entity.setCorpId(corpId);
    		//添加企业id
    		entity.setOrganId(orgId);
    		//添加生成时间
    		entity.setGenTime(new Date());
    		//生成主键
    		commonEntityDao.save(entity);
    		if(count >= 300){
    			this.commonEntityDao.flush();
    			this.commonEntityDao.clear();
    		}
    		
    	}
    	return count;
    }
    
    
    /**
     * 导入晋江电子更纸
     * @param list
     * @param user
     * @param corpId
     * @param orgId
     * @throws Exception
     */
    @Transactional(rollbackFor=Exception.class)
    public int saveJinJiangToDB(List<EaiIttriplogEntity> list, SysUserEntity user,String corpId,String orgId) throws Exception {
    	SimpleDateFormat execlDate = new SimpleDateFormat("yyyy-MM-dd");
    	SimpleDateFormat sqlDate=new SimpleDateFormat("yyyyMMdd");
    	SimpleDateFormat execlTime = new SimpleDateFormat("HH:mm:ss");
    	SimpleDateFormat sqlTime=new SimpleDateFormat("HHmmss");
    	Map<String,String> mapId = new HashMap<String,String>();
    	int count = 0;
    	Map<String, String> map = new HashMap<String, String>();
    	String dispatchstarttime = "";
    	String endtriptime = "";
    	String rundate = "";
    	for(EaiIttriplogEntity entity:list){
    		//生成主键
    		if(!PubUtil.isEmpty(entity.getDispatchstarttime()) || !PubUtil.isEmpty(entity.getEndtriptime())){
    			Date date1 = execlTime.parse(entity.getDispatchstarttime());
    			dispatchstarttime=sqlTime.format(date1);
        		Date date2 = execlTime.parse(entity.getEndtriptime());
        		endtriptime=sqlTime.format(date2);
    		}else{
    			dispatchstarttime = "000000";
    			endtriptime = "000000";
    			continue;
    		}
    		Date date3 =  execlDate.parse(entity.getRundate());
    		rundate = sqlDate.format(date3);
    		String busCode = entity.getBuscodeforshort().replace("闽", "");
    		String rcrdId = getPrimarykey(busCode+rundate+dispatchstarttime+endtriptime);
    		System.out.print(rcrdId+",");
    		entity.setRcrdId(rcrdId);
    		mapId.put("rcrdId", rcrdId);
    		//发出时间
    		entity.setDispatchstarttime(entity.getRundate()+" "+entity.getDispatchstarttime());
    		//到对站时间
    		entity.setEndtriptime(entity.getRundate()+" "+entity.getEndtriptime());
    		//添加机构id
    		entity.setCorpId(corpId);
    		//添加企业id
    		entity.setOrganId(orgId);
    		//添加更新时间
    		entity.setGenTime(new Date());
    		//查询车辆ID
    		map.put("lic_plt_no", entity.getBuscodeforshort());
    		Map<String, String> result = (Map<String, String>) sqlMapDao.selectOne("eleDetail.searchByNo", map);
    		if(!PubUtil.isEmpty(result)){
    			entity.setCarId(result.get("CAR_ID"));
    		}
//    		this.sqlMapDao.delete("eleDetail.deleteById", mapId);
    		int a = (int) this.sqlMapDao.selectOne("searchById", mapId);
    		if(a>0){
    			this.commonEntityDao.update(entity);
    		}else{
    			this.commonEntityDao.save(entity);
    		}
    		count++;
    		if(count >= 300){
    			this.commonEntityDao.flush();
    			this.commonEntityDao.clear();
    		}
    	}
    	return count;
    }
    
    //触发线路偏移的纠正算法
    public void triggerAlgorithm(String corpId){
    	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    	Date date = new Date();
    	String time = format.format(date);
    	Map<String, Object> paraMap = new HashMap<String, Object>();
        paraMap.put("corpId", corpId);
        paraMap.put("beginTime",time );
        paraMap.put("endTime",time);
        // 调用存储过程“PC_BS_TMP_ENE_DET”重新生成“T_BS_TMP_ENE_DET”数据
        try {
        	this.sqlMapDao.update("eleDetail.buildEnerConsStatBevMidTab", paraMap);
            //modifiy by qianjy 增加调取存储过程反馈信息的接受处理
            if("-1".equals(paraMap.get("oRetCode").toString())){
            	throw new Exception(paraMap.get("oRetNote").toString());
            };
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("Run the stored procedure to create T_BS_TMP_ENE_DET failure");
        }
    }
    
    //不满32位后面自动补0
    public String getPrimarykey(String rcrdId){
    	int n = 32;
    	rcrdId = rcrdId+String.format("%1$0"+(n-rcrdId.length())+"d",0);
    	return rcrdId;
    }
    
    
    public String getStationCode(String startstopname,String rundirection) throws Exception  {
    	String code=null;
    	Map<String,String> map = new HashMap<String,String>();
    	map.put("startstopname", startstopname);
		map.put("rundirection", rundirection);
		Map<String, String> result =  (Map<String, String>) sqlMapDao.selectOne("eleDetail.searchStationCode", map);
		if(PubUtil.isEmpty(result)){
			startstopname=startstopname.replace("站", "");
			map.put("startstopname", startstopname);
			result = (Map<String, String>) sqlMapDao.selectOne("eleDetail.searchStationCode", map);
			if(PubUtil.isEmpty(result)){
				startstopname=startstopname.replace("1", "");
				map.put("startstopname", startstopname);
				result =  (Map<String, String>) sqlMapDao.selectOne("eleDetail.searchStationCode", map);
			}
		}
		if(!PubUtil.isEmpty(result)){
			code=(String) result.get("STN_ID");
		}
		return code;
    }
    
    
}
